package cs4295asg2.stockfinder;


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint({ "NewApi", "ValidFragment" })
public class FavouriteStocks extends Activity {
	protected static final String View = null;
		List<StockTarget> stockList;
		ArrayAdapter<StockTarget> adapter;

	 	@Override
	    protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_favourite_list);
	        TextView tv=(TextView)findViewById(R.id.f_stock_target);
	        tv.setBackgroundColor(Color.rgb(46, 139, 87));
	        tv = (TextView)findViewById(R.id.f_stock_number);
	        tv.setBackgroundColor(Color.rgb(46, 139, 87));
	        
	        Intent i = getIntent();
	 
	        stockList = new ArrayList();
	        
	        // Load data by using SharedPreferences
	        SharedPreferences settings=getSharedPreferences("task_Pref",Context.MODE_PRIVATE);
        	int count=settings.getInt("tCount", 0);
        	String d;
        	for (int j=0;j<count;j++){
        		d=settings.getString("Task_"+j, "ERROR");
        		String [] sArray = d.split(",");
        		String stNo = sArray[0];
        		double currP = Double.parseDouble(sArray[1]);
        		double targetP = Double.parseDouble(sArray[2]);
        		StockTarget stTemp = new StockTarget(stNo, currP);
        		stTemp.setTargetPrice(targetP);
        		stockList.add(stTemp);
        	}
        	
        	// if there is an extra to be got, then add it to the list
	        if(i.getStringExtra(StockDetails.STOCK_NO)!=null){
	        	String stockNo = i.getStringExtra(StockDetails.STOCK_NO).toString();
	        	double currPrice = Double.parseDouble(i.getStringExtra(StockDetails.CURR_PRICE).toString());
	        	StockTarget st = new StockTarget(stockNo, currPrice);
	            stockList.add(st);     
	        }
	        

	        adapter = new ArrayAdapter<StockTarget> (this,
					android.R.layout.simple_expandable_list_item_1,
					stockList);
	        
	        final ListView lv=(ListView)findViewById(R.id.stockList);
			lv.setAdapter(adapter);

			lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
			
			lv.setMultiChoiceModeListener(new MultiChoiceModeListener(){
				public void onItemCheckedStateChanged(ActionMode mode,
				int position,long id, boolean checked){
					View v=(View)lv.getChildAt(position);
					if (checked)
						v.setBackgroundColor(0xFF0099cc);
					else
						v.setBackgroundColor(Color.WHITE);
				}

				@Override
				public boolean onActionItemClicked(ActionMode mode,MenuItem item) {
					if(item.getItemId()==R.id.stock_list_menu_Del){
						int count=lv.getCount();
						SparseBooleanArray checked=lv.getCheckedItemPositions();
						for (int i=count-1;i>=0;i--){
								if (checked.get(i)){
									Log.i("cab","Item "+Integer.toString(i)+"selected");
									View v=(View)lv.getChildAt(i);
									v.setBackgroundColor(Color.WHITE);
									stockList.remove(i);
								}
						}
						adapter.notifyDataSetChanged();
						return true;
					}
					else if(item.getItemId()==R.id.stock_list_menu_SetTarget){
						int count=lv.getCount();					
						SparseBooleanArray checked=lv.getCheckedItemPositions();
					    
						for (int i=count-1;i>=0;i--){
							if (checked.get(i)){
								FireMissilesDialogFragment f = new FireMissilesDialogFragment(i);
								f.show(getFragmentManager(), "missiles");
								View v=(View)lv.getChildAt(i);
								v.setBackgroundColor(Color.WHITE);
							}
						}	
						adapter.notifyDataSetChanged();
						return true;
					}
					return false;
				}

				@Override
				public boolean onCreateActionMode(ActionMode mode, Menu menu) {
					MenuInflater inflater = mode.getMenuInflater();
					inflater.inflate(R.menu.cab_favourite_list, menu);
					return true;
				}

				@Override
				public void onDestroyActionMode(ActionMode mode) {	
					int count=lv.getCount();
					SparseBooleanArray checked=lv.getCheckedItemPositions();
					for (int i=count-1;i>=0;i--){
						if (checked.get(i)){
							View v=(View)lv.getChildAt(i);
							v.setBackgroundColor(Color.WHITE);
						}
					}
				}

				@Override
				public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
					return false;
				}
			});
	    }
	 	
	 	@Override
	 	protected void onStop(){
	 		super.onStop();
	 		// save data
	 		SharedPreferences settings=getSharedPreferences("task_Pref",Context.MODE_PRIVATE);
	 		SharedPreferences.Editor editor=settings.edit();
	 		int c=stockList.size();
	 		editor.putInt("tCount", c);
	 		for (int i=0;i<c;i++){
	 			editor.putString("Task_"+i, stockList.get(i).getString());
	 		}
	 		editor.commit();
	 	}
	 	
	 	
	    @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        // Inflate the menu; this adds items to the action bar if it is present.
	        getMenuInflater().inflate(R.menu.activity_main, menu);
	        return true;
	    }
	    
	    public class FireMissilesDialogFragment extends DialogFragment {
	    	private int index;
		    public FireMissilesDialogFragment(int i) {
				index = i;
			}

			@Override
		    public Dialog onCreateDialog(Bundle savedInstanceState) {
		        // Use the Builder class for convenient dialog construction
		        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		        LayoutInflater inflater = getActivity().getLayoutInflater();
		        final EditText ed = new EditText(getActivity());
		        builder.setTitle("Set Your Target");
		        builder.setView(ed)
		               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                   public void onClick(DialogInterface dialog, int id) {
		                       // FIRE ZE MISSILES!
		                	   double price;
		                	   if(ed.getText().toString()!=null)
		                		    price = Double.parseDouble(ed.getText().toString());
		                	   else
		                		    price = 0;
		                	   
		                	   stockList.get(index).setTargetPrice(price);
		                   }
		               })
		               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		                   public void onClick(DialogInterface dialog, int id) {
		                       // User cancelled the dialog
		                   }
		               });
		        // Create the AlertDialog object and return it
		        return builder.create();
		    }
		}
	    
}
